package leetcode.editor.cn.q1_300.q;

/**
 * @author qidi
 * @date 2021-11-02 10:31:07
 */
class Q0024_SwapNodesInPairs {


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public ListNode swapPairs(ListNode head) {
            if (head == null) return null;
            if (head.next == null) return head;

            ListNode H = null;
            ListNode c = null;
            ListNode tmp;
            ListNode cur = head;
            while (cur != null) {
                if (cur.next == null) {
                    c.next = cur;
                    break;
                }
                tmp = cur.next.next;
                if (H == null) {
                    H = cur.next;
                    H.next = cur;
                    c = cur;
                } else {
                    c.next = cur.next;
                    c.next.next = cur;
                    c = c.next.next;
                }
                c.next = null;
                cur = tmp;
            }
            return H;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)


    public static void main(String[] args) {
        Solution solution = new Q0024_SwapNodesInPairs().new Solution();
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        ListNode n5 = new ListNode(5);
        n4.next = n5;
        ListNode n6 = new ListNode(6);
        n5.next = n6;

        solution.swapPairs(n1);
    }
}